import Axios from 'axios'
import qs from 'qs'
import store from '../store'
import {baseUrl, timeOut} from "../myConfig";
import {printMsg, utf8_to_b64} from "./util";

let ajax = Axios.create({
  baseURL: baseUrl,
  timeout: timeOut

})
ajax.interceptors.request.use(request => {
    if (request.method === "post") {
      // console.log(request.data instanceof FormData);
      if (!(request.data instanceof FormData)) {
        request.data = JSON.stringify(request.data)
        request.headers['Content-Type'] = 'application/json'
        printMsg('stringfied');
      } else {
        printMsg("use original formdata")
      }
    }
    return request
  }, error => {
    return Promise.reject(error)
  }
)

ajax.interceptors.response.use(response => {
    if (response.data.code === "0000") {
      return response.data
    } else {
      return Promise.reject(response.data)
    }
  }, error => {
    if (error.message.includes('timeout')) {
      return Promise.reject({msg: '请求超时，请稍后重试'})
    }else if (error.message.includes('refused')) {
      return Promise.reject({msg: '网络不佳，请稍后重试'})
    }else if (error.message.includes('Network Error')) {
      return Promise.reject({msg: '网络不佳，请稍后重试'})
    }else if (error.message.includes('Request failed')) {
      return Promise.reject({msg: '服务器异常，请稍后重试'})
    }
    console.log(error)
    return Promise.reject(error.response.data)
  }
)

// ajax.defaults.withCredentials = true
ajax.defaults.headers.common['Access-Control-Allow-Origin'] = '*'

ajax.updateAuth = () => {
  ajax.defaults.headers.common['Authorization'] = store.state.token
  ajax.defaults.headers.common['Nickname'] = utf8_to_b64(store.state.nickname)
}
ajax.encode = (a) => window.btoa(encodeURIComponent(a))

export default ajax
